from .rerank import resort
from tipsz8 import saveLocalData, loadLocalData, clear_cache, getFileUTime
import json
import random
import os
arr = []
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data_class"))
file_path = os.path.join(base_dir, "p_groups.json")
file_path1 = os.path.join(base_dir, "u_groups.json")
file_path2 = os.path.join(base_dir, "c_groups.json")
file_path3 = os.path.join(base_dir, "g_groups.json")

p_data = loadLocalData(file_path) or {}
# data = loadLocalData("shop.json") or []
p_data = loadLocalData(file_path) or {}
u_data = loadLocalData(file_path1) or {}
c_data = loadLocalData(file_path2) or {}
g_data = loadLocalData(file_path3) or {}

# data = data[:100]
# for i in data:
#     arr.append(json.dumps(i, ensure_ascii=False))
# query = "5000-8000 主流游戏 Ryzen 5"


def select_data(query,query_txt):
    if query.price:
        return p_data.get(query_txt, [])
    if query.useplan:
        return u_data.get(query_txt, [])
    if query.cpu:
        # print(c_data)
        # print(f"query_txt:{query_txt}")
        return c_data.get(query_txt, [])
    if query.gpu:
        return g_data.get(query_txt, [])
    

def search(query):
    query_txt = ""
    if query.price:
        query_txt += query.price + " "
    if query.useplan:
        query_txt += query.useplan + " "
    if query.cpu:
        query.cpu = query.cpu.replace('\u00A0', ' ')
        query_txt += query.cpu + " "
    if query.gpu:
        query_txt += query.gpu 
    # query_txt = query.price + " " + query.useplan + " " + query.cpu + " " + query.gpu
    query_txt = query_txt.strip()
    print(f"query_txt:{query_txt}")
    arr = select_data(query,query_txt)

    arr = sorted(arr, key=lambda x: len(json.dumps(x, ensure_ascii=False)), reverse=True)[:70]
    # arr = random.sample(arr, min(len(arr), 50))
    # if not arr:
    #     return []
    print(len(arr))
    if query.question:
        # arrtemp = [json.dumps(i, ensure_ascii=False) for i in arr]
        return resort(query.question, arr)
    else:
        return [item.get("ID") for item in arr[:5]]

    # print(f"arr: {len(arr)}")
    # arr = [json.dumps(i, ensure_ascii=False) for i in arr]
    # print(f"arr: {len(arr)}")
    # resort(query.text, arr)
    # return arr
# resort(query, arr)

# result = search({"price": "3000-5000", "useplan": "", "cpu": "", "gpu": "","question":"rtx 4060"})
# print(f"result: {result}")

def search_rerank(query):
    if query.price:
        price = query.price.replace("￥", "").replace(" ", "")  
        start, end = price.split("-")
        if "万" in start:
            numeric_part = float(start.replace("万", ""))
            start = str(int(numeric_part * 10000))
        if "万" in end:
            numeric_part = float(end.replace("万", ""))
            end = str(int(numeric_part * 10000))
        query.price = f"{start}-{end}"
    return search(query)

